#include <iostream>
#include <map>
#include <utility>
#include <string>

using std::cout;
using std::endl;
using std::map;
using std::pair;
using std::make_pair;
using std::string;

template <typename Container>
void display(const Container &con)
{
    for(auto &elem : con)
    {
        cout << elem.first << "  " << elem.second << endl;
    }
}

void test()
{
    //map的特征
    //1、存放的是key-value类型，key值是唯一的，不能重复，value
    //既可以重复也可以不重复
    //2、默认情况下，会按照key值进行升序排列
    //3、底层使用的也是红黑树
    map<int, string> number = {
    /* map<int, string, std::greater<int>> number = { */
        pair<int, string>(1, "wuhan"),
        pair<int, string>(9, "beijing"),
        pair<int, string>(9, "jing"),
        {3, "wangdao"},
        {5, "hubei"},
        {8, "wangdao"},
        make_pair(4, "shanghai"),
        make_pair(7, "shanghai"),
    };
    display(number);

    cout << endl << "map的查找" << endl;
    size_t cnt = number.count(3);
    cout << "cnt = " << cnt << endl;

    map<int, string>::iterator it = number.find(4);
    if(it != number.end())
    {
        cout << "该元素在set中 : " 
             << it->first << "  "
             << it->second << endl;
    }
    else
    {
        cout << "该元素不在map中" << endl;
    }

    cout <<endl << "insert操作" << endl;
    pair<map<int, string>::iterator, bool> ret = 
        /* number.insert(pair<int, string>(6, "nanjing")); */
        /* number.insert(make_pair(6, "nanjing")); */
        number.insert({6, "nanjing"});
    if(ret.second)
    {
        cout << "插入成功 " << ret.first->first 
             << "    " << ret.first->second << endl;
    }
    else
    {
        cout << "插入失败,该元素存在map中" << endl;
    }
    display(number);

    cout << endl << "下标操作" << endl;
    cout << "number[5] = " << number[5] << endl;//查找
    cout << "number[2] = " << number[2] << endl;//插入
    display(number);

    cout << endl;
    //T &operator[](const Key &)
    number[2] = "wangdao";//修改
    /* number.operator[](2).operator=("wangdao"); */
    /* const map<int, string> tmp = {{1, "hello"}, {2, "wuhan"}}; */
    /* cout << tmp[2] << endl; */
    display(number);
}

int main(int argc, char *argv[])
{
    test();
    return 0;
}

